package com.cp.rabbitmq.fairworkqueue;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


import com.cp.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;


/* /**
   * @author Coder编程
   * @Title: ConsumerOne
   * @Package:  com.cp.rabbitmq.fairworkqueue
   * @Description: 
   * @version V1.0
   * @date 2019/7/10 19:44
 **/

public class ConsumerOne {
	private static final String  QUEUE_NAME="TEST_FAIR_WORK_QUEUE";
	
	public static void main(String[] args) throws IOException, TimeoutException {
		
		//获取连接
		Connection connection = ConnectionUtils.getConnection();
		//获取channel
		final Channel channel = connection.createChannel();
		//声明队列
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		
		channel.basicQos(1);//保证一次只分发一个  
		
		//定义一个消费者
		Consumer consumer=new DefaultConsumer(channel){
			//消息到达 触发这个方法
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope,
					BasicProperties properties, byte[] body) throws IOException {
			 
				String msg=new String(body,"utf-8");
				System.out.println("[ConsumerOne] Received msg:"+msg);
				
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally{
					System.out.println("[ConsumerOne] done ");
					channel.basicAck(envelope.getDeliveryTag(), false);
				}
			}
		};
		
		boolean autoAck=false;//自动应答 false
		channel.basicConsume(QUEUE_NAME,autoAck , consumer);
	}

}
